﻿<%@ Page Title="Generator" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    Inherits="Generator_v2" ValidateRequest="false" CodeBehind="Generator_v2.aspx.cs" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/themes/base/jquery-ui.css"
        type="text/css" media="all" />
    <link href="Styles/StyleSheet.css" rel="stylesheet" type="text/css" />
    <link href="Styles/start/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        #FinishedText
        {
            width: 602px;
            height: 36px;
        }
    </style>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <%--<script src="Scripts/jquery-1.8.0.js" type="text/javascript"></script>--%>
    <%--<script src="Scripts/jquery-1.8.2.js" type="text/javascript"></script>--%>
    <script src="Scripts/jquery-1.7.js" type="text/javascript"></script>
    <%--<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>--%>
    <%--    <script type="text/javascript" src="Scripts/ui/jquery.ui.core.js"></script>
	<script type="text/javascript" src="Scripts/ui/jquery.ui.widget.js"></script>
	<script type="text/javascript" src="Scripts/ui/jquery.ui.position.js"></script>
	<script type="text/javascript" src="Scripts/ui/jquery.ui.autocomplete.js"></script>--%>
    <script src="Scripts/jquery-ui-1.9.1.custom/development-bundle/ui/jquery.ui.core.js"
        type="text/javascript"></script>
    <script src="Scripts/jquery-ui-1.9.1.custom/development-bundle/ui/jquery.ui.position.js"
        type="text/javascript"></script>
    <script src="Scripts/jquery-ui-1.9.1.custom/development-bundle/ui/jquery.ui.menu.js"
        type="text/javascript"></script>
    <script src="Scripts/jquery-ui-1.9.1.custom/development-bundle/ui/jquery.ui.widget.js"
        type="text/javascript"></script>
    <script src="Scripts/jquery-ui-1.9.1.custom/development-bundle/ui/jquery.ui.autocomplete.js"
        type="text/javascript"></script>
    <script src="Scripts/jquery-ui-1.9.1.custom/development-bundle/ui/jquery-ui.custom.js"
        type="text/javascript"></script>
    <%--	<script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script>
    --%>
    <script src="Scripts/nicEdit.js" type="text/javascript"></script>
    
    <script src="Scripts/rangy-1.2.3/uncompressed/rangy-core.js" type="text/javascript"></script>
    <script src="Scripts/rangy-1.2.3/uncompressed/rangy-serializer.js" type="text/javascript"></script>
    <script src="Scripts/rangy-1.2.3/uncompressed/rangy-cssclassapplier.js" type="text/javascript"></script>
    <script src="Scripts/rangy-1.2.3/uncompressed/rangy-selectionsaverestore.js" type="text/javascript"></script>

    <style>
        .ui-autocomplete
        {
            max-height: 300px;
            overflow-y: auto; /* prevent horizontal scrollbar */
            overflow-x: hidden; /* add padding to account for vertical scrollbar */
            padding-right: 20px;
        }
        /* IE 6 doesn't support max-height
	 * we use height instead, but this forces the menu to always be this tall
	 */
        * html .ui-autocomplete
        {
            height: 300px;
        }
    </style>
    <script type="text/javascript">

        var browserName = getBrowserName();

        //try to do java before postback
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_initializeRequest(InitializeRequest);

        function InitializeRequest(sender, args) {
            $("#<%=HiddenTextArea.ClientID%>").val(nicEditors.findEditor('FinishedText').getContent());
        }


        var nic;
        bkLib.onDomLoaded(function () {
            try {
                startNicEditor();
                //setting the content from the hidden text area to nicEdit
                nicEditors.findEditor('FinishedText').setContent($("#<%=HiddenTextArea.ClientID%>").val());
            }
            catch (ex) { }

        });


        function getBrowserName() {
            var browserName1 = navigator.appName;
            if (browserName1 == "Microsoft Internet Explorer") return "Microsoft Internet Explorer";
            else if (browserName1 == "Opera") return "Opera";
            else if (browserName1 == "Netscape") {
                var stringContainingName = navigator.userAgent;
                if (stringContainingName.match(/Safari/gi) == "Safari") {
                    if (stringContainingName.match(/Chrome/gi) == "Chrome") return "Chrome";
                    else return "Safari";
                }
                else if (stringContainingName.match(/Chrome/gi) == "Chrome") return "Chrome";
                else if (stringContainingName.match(/Firefox/gi) == "Firefox") return "Firefox";
                else return "unknown";
            }
            else return "unknown";
        }
    </script>
    <div class="panel">
        <br />
        <br />
        <br />
        <br />
        <asp:Label ID="SpecialityLabel" runat="server" Text="Selecteaza specialitatea"></asp:Label>
        <br />
        <asp:DropDownList ID="SelectSpeciality" runat="server" Width="120px" CausesValidation="True"
            DataSourceID="DBConnectionString" DataTextField="NumeSpecialitate" DataValueField="NumeSpecialitate"
            AutoPostBack="True">
            <asp:ListItem Selected="True"></asp:ListItem>
            <asp:ListItem>Spec 1</asp:ListItem>
            <asp:ListItem>Spec 2</asp:ListItem>
            <asp:ListItem>Spec 3</asp:ListItem>
        </asp:DropDownList>
        <asp:SqlDataSource ID="DBConnectionString" runat="server" ConnectionString="<%$ ConnectionStrings:SpecialityDropDownConnectionString %>"
            SelectCommand="SELECT [ID], [NumeSpecialitate] FROM [DenumiriSpecialitati] ORDER BY [NumeSpecialitate]">
        </asp:SqlDataSource>
        <br />
        <br />
        <asp:CheckBox ID="ModelActive" runat="server" Text="Model Activ" AutoPostBack="True"
            OnCheckedChanged="ModelActive_CheckedChanged" />
        <br />
        <asp:Label ID="ModelLabel" runat="server" Text="Selecteaza Modelul"></asp:Label>
        <br />
        <asp:DropDownList ID="SelectModel" runat="server" Width="120px" AutoPostBack="True"
            Enabled="False" DataSourceID="ModelDropDownConnectionString" DataTextField="NumeModel"
            DataValueField="NumeModel">
            <asp:ListItem Selected="True"></asp:ListItem>
            <asp:ListItem>Model 1</asp:ListItem>
            <asp:ListItem>Model 2</asp:ListItem>
            <asp:ListItem>Model etc...</asp:ListItem>
        </asp:DropDownList>
        <br />
        <br />
        <asp:Label ID="Label3" runat="server" Text="Selecteaza genul"></asp:Label>
        <br />
        <asp:RadioButtonList ID="MFRadioButtonList" runat="server" RepeatLayout="Flow" OnSelectedIndexChanged="MFRadioButtonList_SelectedIndexChanged"
            AutoPostBack="True">
            <asp:ListItem>Masculin</asp:ListItem>
            <asp:ListItem>Feminin  </asp:ListItem>
            <asp:ListItem Selected="True">Ambele</asp:ListItem>
        </asp:RadioButtonList>
        <asp:SqlDataSource ID="ModelDropDownConnectionString" runat="server" ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
            SelectCommand="SELECT [ID], [NumeModel], [TextModel], [Specialitate] FROM [DenumiriModele] WHERE ([Specialitate] = @Specialitate)  ORDER BY [NumeModel]">
            <SelectParameters>
                <asp:ControlParameter ControlID="SelectSpeciality" Name="Specialitate" PropertyName="SelectedValue"
                    Type="String" />
            </SelectParameters>
        </asp:SqlDataSource>
    </div>
    <h2>
    </h2>
    <div class="multipleWords">
        <h3>
            <asp:Label ID="ModelTextTitle" runat="server" Text="Textul Modelului:" Height="30px"
                Visible="False"></asp:Label></h3>
        <asp:Panel ID="ModelText" runat="server" ScrollBars="Vertical" Width="777px" Height="190px"
            BorderColor="#0099FF" BorderWidth="1px" Visible="False">
            <asp:DataList ID="DataList1" runat="server" DataKeyField="ID" DataSourceID="ModelDataSource">
                <ItemTemplate>
                    <asp:Label ID="TextModelLabel" runat="server" Text='<%# Eval("TextModel") %>' />
                    <br />
                </ItemTemplate>
            </asp:DataList>
            <asp:SqlDataSource ID="ModelDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
                SelectCommand="SELECT [ID], [NumeModel], [TextModel], [Specialitate] FROM [DenumiriModele] WHERE (([Specialitate] = @Specialitate) AND ([NumeModel] = @NumeModel))">
                <SelectParameters>
                    <asp:ControlParameter ControlID="SelectSpeciality" Name="Specialitate" PropertyName="SelectedValue"
                        Type="String" />
                    <asp:ControlParameter ControlID="SelectModel" Name="NumeModel" PropertyName="SelectedValue"
                        Type="String" />
                </SelectParameters>
            </asp:SqlDataSource>
        </asp:Panel>
        <br />
        <br />
        <h3>
            <asp:Label ID="Label4" runat="server" Text="Textul Generatorului:"></asp:Label></h3>
        <div id="FinishedText" cols="20" rows="2" style="width: 780px; height: 200px;">
        </div>
        <asp:HiddenField ID="HiddenTextArea" runat="server" />
        <asp:HiddenField ID="GenreHiddenTextArea" runat="server" />
        <br />
        <br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        <input type="button" value="Save Postion" onclick="SavePosition();return false;" />
        <input type="button" value="Restore Postion" onclick="RestorePosition();return false;" />
        <div id="area" style="width: 300px; height: 300px;" onblur="onDivBlur();" onmousedown="return cancelEvent(event);"
            onclick="return cancelEvent(event);" contenteditable="true" onmouseup="saveSelection();"
            onkeyup="saveSelection();" onfocus="restoreSelection();">
        </div>
        <script type="text/javascript">
            var savedRange, isInFocus;
            function saveSelection() {
                if (window.getSelection)//non IE Browsers
                {
                    savedRange = window.getSelection().getRangeAt(0);
                }
                else if (document.selection)//IE
                {
                    savedRange = document.selection.createRange();
                }
            }

            function restoreSelection() {
                isInFocus = true;
                document.getElementById("area").focus();
                if (savedRange != null) {
                    if (window.getSelection)//non IE and there is already a selection
                    {
                        var s = window.getSelection();
                        if (s.rangeCount > 0)
                            s.removeAllRanges();
                        s.addRange(savedRange);
                    }
                    else
                        if (document.createRange)//non IE and no selection
                        {
                            window.getSelection().addRange(savedRange);
                        }
                        else
                            if (document.selection)//IE
                            {
                                savedRange.select();
                            }
                }
            }
        </script>
    </div>
    <div id="imHere2" style="position: absolute; bottom: 100px">
    </div>
    <!-- start-stop NicEdit, get browser -->
    <script type="text/javascript">

        function startNicEditor() {
            nic = new nicEditor({ fullPanel: false, position: { my: "right top", at: "right bottom" }, iconsPath: 'img/nicEditorIcons.gif', buttonList: ['fontSize', 'fontFamily', 'forecolor', 'bold', 'italic', 'underline', 'strikethrough', 'left', 'center', 'right'], externalCSS: 'Styles/Site.css' })
			.panelInstance('FinishedText', { hasPanel: true });
            nic.addEvent('blur',
				function () {
				    //setting the content from the hidden text area to nicEdit
				    currentEditorText = nicEditors.findEditor('FinishedText').getContent();
				    if (currentEditorText != $("#<%=HiddenTextArea.ClientID%>").val()) {

				        //x                        updateGeneratorAfterNicEdited();
				        //alert("nicedit text: \n" + "|" + nicEditors.findEditor('FinishedText').getContent() + "|");
				        $("#<%=HiddenTextArea.ClientID%>").val(currentEditorText);

				    }
				});
        }

        function updateGeneratorAfterNicEdited() {

            alert("nicedit text: \n" + "|" + nicEditors.findEditor('FinishedText').getContent() + "|");
            var nicTextTags = nicEditors.findEditor('FinishedText').getContent();

            //nicTextTags = nicTextTags.replace(/</, "< ");

            alert("we've got " + browserName);

            switch (browserName) {
                case "Chrome":
                    {
                        nicTextTags = nicTextTags.replace(/<br>/gi, "");
                        //nicTextTags = nicTextTags.replace(/&nbsp;/gi, "");
                        nicTextTags = nicTextTags.replace(/<div/gi, "998877<div");
                    }
                    break;
                case "Microsoft Internet Explorer":
                    {
                        nicTextTags = nicTextTags.replace(/&nbsp;/gi, " ");
                        //nicTextTags = nicTextTags.replace(/&nbsp;/gi, "");
                        nicTextTags = nicTextTags.replace(/<p/gi, "998877<p");
                        nicTextTags = nicTextTags.replace(/998877/, "");
                    }
                    break;
                case "Firefox":
                    {
                        nicTextTags = nicTextTags.replace(/<br/gi, "998877<br");
                        nicTextTags = nicTextTags.replace(/&nbsp;/gi, " ");
                        nicTextTags = nicTextTags.replace(/998877<br>([^998877<br>]*)$/, '$1'); //remove the last <br>, it's redundant
                    }
                    break;
                case "Opera":
                    {
                        nicTextTags = nicTextTags.replace(/&nbsp;/gi, " ");
                        //nicTextTags = nicTextTags.replace(/<br>/gi, "");
                        nicTextTags = nicTextTags.replace(/<p/gi, "998877<p");
                        nicTextTags = nicTextTags.replace(/998877/, "");
                    }
                    break;
                case "Safari":
                    {
                        //nicTextTags = nicTextTags.replace(/&nbsp;/gi, "");
                        nicTextTags = nicTextTags.replace(/<div/gi, "998877<div");
                        //nicTextTags = nicTextTags.replace(/998877/, "");
                    }
                    break;
                default:
                    {
                        nicTextTags = nicTextTags.replace(/<p><br>/gi, "<p>");
                        nicTextTags = nicTextTags.replace(/<div/gi, "998877<div"); // 998877 is place holder for future \n
                        nicTextTags = nicTextTags.replace(/<p/gi, "998877<p");
                        nicTextTags = nicTextTags.replace(/<br/gi, "998877<br");
                    }
            }


            alert(nicTextTags);


            $(function () {
                var zxc2 = $("<span>" + nicTextTags + "</span>").text(); //remove html tags
                zxc2 = zxc2.replace(/998877/gi, "\n");
                alert(my_function().toString);
            });



        }

        function removeHtmlTags(text) {
            var zxc2 = $("<span>" + text + "</span>").text(); //remove html tags
            zxc2 = zxc2.replace(/998877/gi, "\n");
            return zxc2;
        }



    </script>
    <!-- AUTOCOMPLETE function -->
    <script type="text/javascript">
        my_function = null;
        
        var tempString = "";
        currentEditorText = "";
        var tempVar;
        var modelTextOriginal = '';
        var TagsPlacementArray = new Array();
        var savedNicCursorPosition = nicEditors.findEditor('FinishedText');


        try {
            modelTextOriginal = $("span#MainContent_DataList1_TextModelLabel_0").html(); // document.getElementById("MainContent_DataList1_TextModelLabel_0").innerHTML;
            //alert(modelTextOriginal);
        } catch (ex) {
            //alert("NO Model text available"); 
        }


        var rangySavedSel = null;
        var rangySavedSelActiveElement = null;

        function rangySaveSelection() {
            // Remove markers for previously saved selection
            if (rangySavedSel) {
                rangy.removeMarkers(rangySavedSel);
            }
            rangySavedSel = rangy.saveSelection();
            rangySavedSelActiveElement = document.activeElement;
        }

        function rangyRestoreSelection() {
            if (rangySavedSel) {
                rangy.restoreSelection(rangySavedSel, true);
                rangySavedSel = null;
                window.setTimeout(function () {
                    if (rangySavedSelActiveElement && typeof rangySavedSelActiveElement.focus != "undefined") {
                        rangySavedSelActiveElement.focus();
                    }
                }, 1);
            }
        }

        bkLib.onDomLoaded(function () {
            //var currentNicEditContent = nicEditors.findEditor('FinishedText').getContent(),
            //$("#nicEditId").autocomplete({
            $(".nicEdit-main").autocomplete({
                //$("#MainContent_TextBox1").autocomplete({
                source: function (request, response) {
                    $.getJSON("AutoComplete.ashx", {
                        //term: extractLastWithRegex(request.term),
                        //term: "a",
                        //term: extractLast(nicEditors.findEditor('FinishedText').getContent()),
                        term: extractLastWord(request.term)[1],
                        gender: function () {
                            return $("#<%=GenreHiddenTextArea.ClientID%>").val();
                        }
                    }, response);
                },
                position: { my: "right top", at: "right bottom" },
                search: function () {
                    // custom minLength  
                    var term = extractLastWord(nicEditors.findEditor('FinishedText').getContent());
                    if (term.length < 1) {
                        return false;
                    }
                    savedNicCursorPosition = window.getSelection(); //nicEditors.findEditor('FinishedText').getSel();
                    rangySaveSelection();
                },
                focus: function () {
                    // prevent value inserted on focus 
                    return false;
                },
                select: function (event, ui) {

                    //saveNicCursorPosition();
                    //$('#nicCursorPositionDiv').remove();

                    var terms = nicEditors.findEditor('FinishedText').getContent();
                    //terms += "1";
                    var elementsInTerms = extractLastWord(terms);

                    var beginningElement = elementsInTerms[0];
                    var foundWord = elementsInTerms[1];
                    var endingElement = elementsInTerms[2];
                    var foundWordIndex = elementsInTerms[3];

                    //elementsInTerms = ui.item.TextAbreviere;
                    var abreviationText = ui.item.TextAbreviere;
                    abreviationText = getTextFormat(abreviationText);
                    var cursorPositionDiv = "<div class='nicCursorPositionDiv' contentEditable='true' ></div>";

                    terms = beginningElement + abreviationText + endingElement;
                    var curNicEdit = nicEditors.findEditor('FinishedText');

                    //                    var sel = curNicEdit.getSel(), range;
                    //                    //range = sel.createRange();
                    //                    range = curNicEdit.getRng();
                    //                    range.pasteHTML(terms);
                    //                    range.select();
                    //                    range.collapse(false);

                    //curNicEdit.saveRng();
                    //var xxrange = curNicEdit.getRng();
                    //var object_r = ObjectHandler.getCloneOfObject(xxrange);
                    //var xxselection = (window.getSelection) ? window.getSelection() : document.selection; //curNicEdit.getSel();
                    //var object_s = ObjectHandler.getCloneOfObject(xxselection);

                    //                    var clone = (function () {
                    //                        return function (xxselection) { Clone.prototype = xxselection; return new Clone() };
                    //                        function Clone() { }
                    //                    } ());

//                    function clone(obj) {
//                        // A clone of an object is an empty object 
//                        // with a prototype reference to the original.

//                        // a private constructor, used only by this one clone.
//                        function Clone() { }
//                        Clone.prototype = obj;
//                        var c = new Clone();
//                        c.constructor = Clone;
//                        return c;
//                    }

//                    var object_s = clone(xxselection);

                    //		            curNicEdit.saveRng();
                    //var xxselection = curNicEdit.getSel();
                    // curNicEdit.setContent(beginningElement + abreviationText + cursorPositionDiv + endingElement);
                    //var termsr = terms.replace("x", "y");
                    //		            curNicEdit.saveRng();
                    //		            xxrange.commonAncestorContainer.nodeValue = xxrange.commonAncestorContainer.nodeValue.replace("x", "y");
                    //		            xxrange.commonAncestorContainer.data = xxrange.commonAncestorContainer.data.replace("x", "y");
                    //curNicEdit.setContent(termsr);
                    //		            xxrange.startOffset = 5;
                    //		            xxrange.endOffset = 5;
                    //		            curNicEdit.restoreRng();
                    //terms += "1";
                    curNicEdit.setContent(terms);
                    rangyRestoreSelection();
                    //curNicEdit.selRng(savedNicCursorPosition.getRangeAt(0), savedNicCursorPosition);
                    //                    restoreNicCursorPosition();

                    //curNicEdit.selRng(xxrange, xxselection);

                    //                    var press = jQuery.Event("keydown");
                    //                    press.ctrlKey = false;
                    //                    press.which = 51;
                    //                    $("#MainContent_TextBox1").focus();
                    //                    $("#MainContent_TextBox1").trigger(press);

                    //                    range.select();
                    //                    range.collapse(false);

                    //                    var nicRange = curNicEdit.getRng();
                    //                    nicRange.setEnd(3);
                    //                    nicRange.setStart(3);
                    //                    //nicRange.startOffset = terms.length;

                    //                    moveCaretToEnd(curNicEdit);

                    //curNicEdit.getRng().endOffset = curNicEdit.content.length;
                    //var nicRange = curNicEdit.getRng().endOffset;

                    //insertAtCursor(nicEditors.findEditor('FinishedText'), abreviationText);
                    //insertAtCursor(nicEditors.findEditor('FinishedText'), "  2");

                    //tempString = terms;

                    //updateModel(abreviationText, terms.text());
                    //insertAtCursor(curNicEdit, "xx");

                    function moveCaretToEnd(el) {
                        if (typeof el.selectionStart == "number") {
                            el.selectionStart = el.selectionEnd = el.value.length;
                        } else if (typeof el.createTextRange != "undefined") {
                            el.focus();
                            var range = el.createTextRange();
                            range.collapse(false);
                            range.select();
                        }
                    }

                    //                    function createNicCursorPositionDiv() {
                    //                        var cursorPositionDiv = "<div id='nicCursorPositionDiv' contentEditable='true' ></div>";
                    //                        $('#nicCursorPositionDiv').remove();
                    //                        return cursorPositionDiv;
                    //                    }

                    function saveNicCursorPosition() {
                        if (window.getSelection)//non IE Browsers
                        {
                            savedNicCursorPositionRange = window.getSelection().getRangeAt(0);
                        }
                        else if (document.selection)//IE
                        {
                            savedNicCursorPositionRange = document.selection.createRange();
                        }
                    }

                    function restoreNicCursorPosition() {
                        //isInFocus = true;
                        //document.getElementById("nicCursorPositionDiv").focus();
                        $("#nicCursorPositionDiv").parent().focus();
                        if (savedNicCursorPositionRange != null) {
                            if (window.getSelection)//non IE and there is already a selection
                            {
                                var s = window.getSelection();
                                if (s.rangeCount > 0)
                                    s.removeAllRanges();
                                s.addRange(savedNicCursorPositionRange);
                            }
                            else
                                if (document.createRange)//non IE and no selection
                                {
                                    window.getSelection().addRange(savedNicCursorPositionRange);
                                }
                                else
                                    if (document.selection)//IE
                                    {
                                        savedNicCursorPositionRange.select();
                                    }
                        }
                    }

                    //                    function insertAtCursor(editor, value) {
                    //                        var range = editor.getRng();
                    //                        var editorField = editor.selElm();
                    //                        if (editorField.nodeValue == null) {
                    //                            editor.setContent(value);
                    //                        } else {
                    //                            editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) +
                    //                          value +
                    //                          editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);
                    //                            editor.setContent(editorField.nodeValue);
                    //                        }
                    //                    }

                    function insertAtCursor(editor, value) {
                        //var editor = nicEditors.findEditor(editor);
                        var range = editor.getRng();
                        var editorField = editor.selElm();
                        editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) +
							value +
							editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);

                    }

                    function getTextFormat(tempString4) {
                        tempString4 = isTextBold(ui.item.Bold, true) + isTextItalic(ui.item.Italic, true) + getTextSize(ui.item.MarimeText, true)
							+ tempString4 + '&nbsp;'
							+ isTextBold(ui.item.Bold, false) + isTextItalic(ui.item.Italic, false) + getTextSize(ui.item.MarimeText, false);

                        return tempString4;
                    }



                    function updateModel(lastWord, terms) {
                        var modelTextResult = "";
                        var modelTextRed = "<font color='red'>";
                        var generatorTextTemp = terms.split(" ");
                        var generatorTextTemp2 = generatorTextTemp;
                        var matchesInEditor = "";

                        var s1, s2;
                        do {
                            lastWord = $("<div>" + (generatorTextTemp.pop()).toString() + "</div>").text();
                            var lastWordRepetitions = 0;

                            if (lastWord.length > 3) {

                                matchesInEditor = terms.match(/lastWord/gim);
                                if (matchesInEditor) {
                                    lastWordRepetitions = matchesInEditor.length;
                                } else {
                                    lastWordRepetitions = 0;
                                }
                                //                                for (var i = 0; i < terms.length - 1; i++) {
                                //                                    
                                //                                    s1 = generatorTextTemp2[i].toLowerCase();
                                //                                    try {
                                //                                        //get rid of all the signs(except a few) and keep only the letters in the word
                                //                                        s1 = generatorTextTemp2[i].match(/[A-z]/g).toString();
                                //                                    } catch (ex) {
                                //                                    }

                                //                                    if (s1.toLowerCase() == lastWord.toLowerCase().match(/[A-z]/g).toString()) {
                                //                                        lastWordRepetitions++;
                                //                                    }
                                //                                }

                                if (lastWordRepetitions > 0) {

                                    var modelText = modelTextOriginal;
                                    var modelTextTemp = modelText.split(" ");

                                    for (var i = 0; i < modelTextTemp.length; i++) {
                                        s2 = modelTextTemp[i].toLowerCase();
                                        try {
                                            //get rid of all the signs(except a few) and keep only the letters in the word
                                            s2 = modelTextTemp[i].match(/[A-z]/g).toString();
                                        } catch (ex) {
                                        }

                                        if (s2.toLowerCase() == lastWord.toLowerCase().match(/[A-z]/g).toString()) {
                                            lastWordRepetitions--;
                                            if (lastWordRepetitions == 0) {
                                                modelTextTemp.splice(i + 1, 0, "</font><div id='imHere' style='position: absolute; bottom: 100px'></div>");
                                                modelTextResult = modelTextRed + modelTextTemp.join(" ");

                                                document.getElementById("MainContent_DataList1_TextModelLabel_0").innerHTML = modelTextResult;
                                                document.getElementById('imHere').scrollIntoView(true);

                                                break;
                                            }
                                        }
                                    }
                                }
                            }

                        } while (lastWord.length < 4);

                    }

                    return false;
                }
            })
				.data("autocomplete")._renderItem = function (ul, item) {
				    return $("<li></li>")
						.data("item.autocomplete", item)
						.append("<a>" + item.Abreviere + " : " + item.TextAbreviere + " - " + item.Specialitate + "</a>")
						.appendTo(ul);
				};

            function split(val) {
                return val.split(/ \s*|\r\n|\r|\n/);
                //return val.split(" ");
            }

            function splitOnSpaceAndDot(val) {
                return val.split(/[\s.]+/);
            }

            function splitOnSpace(val) {
                return val.split(" ");
            }

            function splitOnEnter(val) {
                return val.split(/\r\n|\r|\n/);
            }

            function splitOnDot(val) {
                return val.split(".");
            }

            function extractLastWord(term) {
                //remove html tags
                var elementsInTerms = new Array();

                elementsInTerms[0] = ""; //begining element
                elementsInTerms[1] = term; //found word
                elementsInTerms[2] = ""; //ending element
                elementsInTerms[3] = -1; //location for first letter of the found word

                var initialText = term;
                var endingElement = "";
                var foundWord = "";
                var beginningElement = "";
                var isWordFound = false;
                var foundWordStartIndex = -1;

                var whiteSpaceRegex = /\s|\n|\r|\t/gim;

                var i = initialText.length - 1;

                while (i >= 0) {
                    while (!isWordFound) {
                        if (isThisWhiteSpace(initialText.charAt(i)) && !isThisSpecialCharacter(initialText.charAt(i))) {
                            while (i >= 0) {
                                beginningElement += initialText.charAt(i);
                                i--;
                            }
                            isWordFound = true; //not found here, but needs to break from while loop
                        }
                        else {
                            while (!isWordFound) {
                                while (initialText.charAt(i) != ">" && initialText.charAt(i) != "<" && !isThisWhiteSpace(initialText.charAt(i))
                                                                    && !isThisSpecialCharacter(initialText.charAt(i)) && i >= 0) {
                                    foundWord += initialText.charAt(i);
                                    isWordFound = true;
                                    foundWordStartIndex = i;
                                    i--;
                                }
                                if (initialText.charAt(i) == ">") {
                                    while (initialText.charAt(i) != "<" && i >= 0) {
                                        if (isWordFound) {
                                            beginningElement += initialText.charAt(i);
                                        } else {
                                            endingElement += initialText.charAt(i);
                                        }
                                        i--;
                                    }
                                }
                                if (initialText.charAt(i) == "<") {
                                    if (isWordFound) {
                                        beginningElement += initialText.charAt(i);
                                    } else {
                                        endingElement += initialText.charAt(i);
                                    }
                                    i--;
                                }
                                if (isThisSpecialCharacter(initialText.charAt(i))) {
                                    if (isWordFound) {
                                        beginningElement += initialText.charAt(i);
                                    } else {
                                        endingElement += initialText.charAt(i);
                                    }
                                    i--;
                                }
                                if (isThisWhiteSpace(initialText.charAt(i)) && !isThisSpecialCharacter(initialText.charAt(i))) {
                                    isWordFound = true; //not found here, but needs to break from while loop
                                }
                            } if (isWordFound) {
                                while (i >= 0) {
                                    beginningElement += initialText.charAt(i);
                                    i--;
                                }
                            }
                        }

                    }
                }

                function isThisWhiteSpace(charToVerify) {
                    if (whiteSpaceRegex.test(charToVerify)) {
                        return true;
                    } else {
                        return false;
                    }
                }

                function isThisSpecialCharacter(charToVerify) {
                    if (escape(charToVerify) == "%uFEFF") {
                        return true;
                    } else {
                        return false;
                    }
                }

                elementsInTerms[0] = beginningElement.split('').reverse().join('');
                elementsInTerms[1] = foundWord.split('').reverse().join('');
                elementsInTerms[2] = endingElement.split('').reverse().join('');
                elementsInTerms[3] = foundWordStartIndex;

                return elementsInTerms;
            }

            function extractLastWithRegex(terms) {
                return null;
            }

            function removeHtmlTags(text) {
                var x = $("<span>" + term + "</span>").text();
                x = splitOnSpaceAndDot(x).pop();
            }
        });


        function isTextBold(b, tag) {
            if ((b != "True") && (b != "False")) return "";

            else if (b == "True") {
                if (tag == true) return "<b>";

                else return "</b>"
            }
            else if (b == "False") return "";
        }


        function isTextItalic(b, tag) {
            if ((b != "True") && (b != "False")) return "";

            else if (b == "True") {
                if (tag == true) return "<i>";

                else return "</i>"
            }
            else if (b == "False") return "";
        }


        function getTextSize(b, tag) {
            if ((b == "") || (b == "NULL") || (b == "null") || (b == "Null") || (b == null) || (b == "False") || (b == "false") || (b == false) || (b == "0") || (b == "undefined") || (b == "UNDEFINED") || (b == "Undefined")) return "";

            else if (tag == true) return "<font size='" + b + "'>";
            else if (tag == false) return "</font>";
        }


        //		var ObjectHandler = {
        //		    //public method
        //		    getCloneOfObject: function (oldObject) {
        //		        var tempClone = {};

        //		        if (typeof (oldObject) == "object")
        //		            for (prop in oldObject)
        //		        //        if (oldObject[prop]) {
        //		                    // for array use private method getCloneOfArray
        //		                if ((typeof (oldObject[prop]) == "object") && ((oldObject[prop] != null) && (oldObject[prop]).__isArray))
        //		                        tempClone[prop] = this.getCloneOfArray(oldObject[prop]);
        //		                        // for object make recursive call to getCloneOfObject
        //		                    else if (typeof(oldObject[prop]) == "object")
        //		                        tempClone[prop] = this.getCloneOfObject(oldObject[prop]);
        //		                        // normal (non-object type) members
        //		                    else
        //		                        tempClone[prop] = oldObject[prop];
        //		         //       }

        //		        return tempClone;
        //		    },

        //		    //private method (to copy array of objects) - getCloneOfObject will use this internally
        //		    getCloneOfArray: function (oldArray) {
        //		        var tempClone = [];

        //		        for (var arrIndex = 0; arrIndex <= oldArray.length; arrIndex++)
        //		            if (typeof (oldArray[arrIndex]) == "object")
        //		                tempClone.push(this.getCloneOfObject(oldArray[arrIndex]));
        //		            else
        //		                tempClone.push(oldArray[arrIndex]);

        //		        return tempClone;
        //		    }
        //		};

        var ObjectHandler = {
            //public method
            getCloneOfObject: function (oldObject, level) {
                var tempClone;
                if (level == undefined)
                    level = 0;
                if (oldObject == null)
                    tempClone = null;
                else if (typeof (oldObject) == "object" && oldObject.length != undefined) {
                    //array
                    tempClone = new Array;
                    for (var i = 0; i < oldObject.length; ++i) {
                        tempClone[tempClone.length] = ObjectHandler.getCloneOfObject(oldObject[i], level + 1);
                    }
                }
                else if (typeof (oldObject) == "object") {
                    //object
                    tempClone = new Object;
                    for (var i in oldObject) {
                        tempClone[i] = ObjectHandler.getCloneOfObject(oldObject[i], level + 1);
                    }
                }
                else {
                    //plain
                    print("Level=" + level + " Plain=" + oldObject);
                    tempClone = oldObject;
                }
                return tempClone;
            }
        };

    </script>
    <br />
</asp:Content>
